package com.coin900.coin.base.utils;

import com.coin900.coin.base.BxConstants;
import com.coin900.coin.persist.coin.CoinTickerVO;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.net.ConnectException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户钱包的工具类
 *
 * @author shui
 * @create 2018-01-24
 **/
public class CoinUserWalletUtils {

    private static final Log logger = LogFactory.getLog(CoinUserWalletUtils.class);

    /**
     * 调用币新接口获取汇率
     *
     * @return
     */
    public static Map<String, Double> getTickers() {

        List<CoinTickerVO> coinTickerList = null;
        try {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> resp = restTemplate.exchange("https://api.coin900.com/api/v2/tickers", HttpMethod.GET, null, String.class);
            String body = resp.getBody();
            String data = JSONObject.fromObject(body).getString("data");
            coinTickerList = new Gson().fromJson(data, new TypeToken<List<CoinTickerVO>>() {
            }.getType());
        } catch (Exception exception) {
            logger.error(exception);
        }

        if (coinTickerList != null) {
            // 组合成 map
            Map<String, Double> tickerMap = new HashMap<>();
            for (CoinTickerVO coinTickerVO : coinTickerList) {
                String code = coinTickerVO.getCode();
                Double last = Double.parseDouble(coinTickerVO.getLast());
                tickerMap.put(code, last);
            }
            return tickerMap;
        } else {
            return null;
        }
    }
}
